package la.renzhen.rtpt.admin.source.jdbc;

import la.renzhen.rtpt.admin.source.ConfigElement;
import la.renzhen.rtpt.admin.source.CenterConfigurationSource;
import lombok.NonNull;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 11/05/2018 4:51 PM
 */
public class JDBCCenterConfigurationSource implements CenterConfigurationSource {

    RowMapper<ConfigElement> rowMapper = (rs, rowNum) -> {
        ConfigElement item = new ConfigElement();
        item.setKey(rs.getString("item_key"));
        item.setValue(rs.getString("item_value"));
        item.setEnvironment(rs.getString("item_env"));
        item.setInfo(rs.getString("item_info"));
        item.setCreateTime(new Date(rs.getLong("item_create_time")));
        return item;
    };

    JdbcTemplate template;

    public JDBCCenterConfigurationSource(JdbcTemplate template) {
        this.template = template;
    }

    @Override
    public List<ConfigElement> loadAll(@NonNull String environment, @NonNull String prefix) {
        StringBuilder sql = new StringBuilder("select * from rtpt where item_env = ?");
        List<String> params = new ArrayList<>();
        params.add(environment);

        if (StringUtils.hasText(prefix)) {
            sql.append(" and item_key like ?");
            params.add(prefix + "%");
        }
        return template.query(sql.toString(), rowMapper, params.toArray());
    }

    @Override
    public List<String> environments() {
        return template.queryForList("select distinct item_env as item_env from rtpt", String.class);
    }

    @Override
    public ConfigElement get(@NonNull String environment, @NonNull String key) {
        return template.queryForObject(
                "select * from rtpt where item_env = ? and item_key = ?",
                rowMapper, environment, key);
    }

    @Override
    public void set(@NonNull ConfigElement item) {
        template.update(
                "insert into rtpt(item_key,item_value,item_env,item_info,item_create_time) " +
                        " value(?,?,?,?,?) " +
                        " ON DUPLICATE KEY UPDATE " +
                        " item_value = ?," +
                        " item_info = ? " +
                        "",
                new Object[]{
                        item.getKey(), item.getValue(), item.getEnvironment(), item.getInfo(), System.currentTimeMillis(),
                        item.getValue(), item.getInfo()
                });
    }

    @Override
    public void del(@NonNull String environment, @NonNull String key) {
        template.update("delete from rtpt where item_key = ? and item_env = ?", key, environment);
    }
}
